var Endpoints = new Object();
var idConuter = 0;
var value="";
var id="";
var saveObject=new Object();
var dataSource=new Object();
var repeatcheck=new Array();
var color1 = "red";
var reloadData=new Object();




var instance = jsPlumb.importDefaults({
	DragOptions : {cursor : 'pointer'	},
	PaintStyle : { strokeStyle:color1 },
	EndpointStyle : { width:20, height:20, strokeStyle:color1 },
	Endpoint : "Rectangle",
	ConnectionOverlays : [[ "Arrow", { width:20, length:30, location:0.5,  }],],
    });
var calEndpointIn1 = {
	endpoint : ["Rectangle",{width:20, length:20 } ],
	connectorOverlays:[  [ "Arrow", { width:20, length:30, location:0.5,  } ],],
	paintStyle : {fillStyle : color1,opacity : 0.5	},
	anchor : [ 0, 0 ],
	isSource : false, 
	scope : "green dot",
	connectorStyle : {strokeStyle : color1,		lineWidth : 3	},
	connector : [ "Bezier", {	curviness : 63	} ],
	maxConnections : 1,
	isTarget : true, 
    onMaxConnections : function(info) {	alert("Cannot drop connection " + info.connection.id + " : maxConnections has been reached on Endpoint " + info.endpoint.id);	}
    };
var calEndpointIn2 = {
	endpoint : ["Rectangle",{width:20, length:20 } ],
	connectorOverlays:[    [ "Arrow", { width:20, length:30, location:0.5,  } ],],
	paintStyle : {		fillStyle : color1,opacity : 0.5	},
	anchor : [ 1, 0 ],
	isSource : false,
	scope : "green dot",
	connectorStyle : {strokeStyle : color1,lineWidth : 3	},
	connector : [ "Bezier", {	curviness : 63	} ],
	maxConnections : 1,
	isTarget : true,
    onMaxConnections : function(info) {alert("Cannot drop connection " + info.connection.id + " : maxConnections has been reached on Endpoint " + info.endpoint.id);}
    };
var calEndpointOut1 = {
	endpoint : ["Rectangle",{width:20, length:20 } ],
	connectorOverlays:[  [ "Arrow", { width:20, length:30, location:0.5,  } ],  ],
	paintStyle : {fillStyle : color1,	opacity : 0.5	},
	anchor : [ 0.5, 1 ],
	isSource : true,
	scope : "green dot",
	connectorStyle : {	strokeStyle : color1,lineWidth : 3	},
	connector : [ "Bezier", {	curviness : 63	} ],
	maxConnections : 1,
	isTarget : false,
    onMaxConnections : function(info) {	alert("Cannot drop connection " + info.connection.id + " : maxConnections has been reached on Endpoint " + info.endpoint.id);},
    };
var dataEndpointOut1 = {endpoint : ["Rectangle",{width:20, length:20 } ],
	connectorOverlays:[    [ "Arrow", { width:20, length:30, location:0.5,  } ],   ],
	paintStyle : {		fillStyle : color1,		opacity : 0.5	},
	anchor : [ 0.5, 1 ],
	isSource : true, 
	scope : "green dot",
	connectorStyle : {		strokeStyle : color1,		lineWidth : 3	},
	connector : [ "Bezier", {		curviness : 63	} ],
	maxConnections : 1,
	isTarget : false, 
    onMaxConnections : function(info) {		alert("Cannot drop connection " + info.connection.id + " : maxConnections has been reached on Endpoint " + info.endpoint.id);}
    };
var commonleft={
		anchors:["BottomCenter", "TopLeft" ],
        endpoints:["Rectangle", "Rectangle" ],
        ConnectionOverlays : [  [ "Arrow", { width:20, length:30, location:0.5,  } ],      	],
     }

var commonright={
	   anchors:["BottomCenter", "TopRight"],
       endpoints:["Rectangle", "Rectangle" ],
       ConnectionOverlays : [  	 [ "Arrow", { width:20, length:30, location:0.5,  } ],],
     }



//生成description的具体函数
function adddescription(id,value,left,top){
	 ;
	$("#scope").append("<div class=\"window\" id=\"" + id + "\" style='left:"+left+";top:"+top+"' sourceType=\"description\"><h1>" + value + "</h1></div>");
	jsPlumb.draggable(id, {containment : "parent"});	
	Endpoints[id] = new Array();		
	test = jsPlumb.addEndpoint(id, dataEndpointOut1);
	Endpoints[id].push(test);		
	deleteFunction();
	idConuter++;
}
//生成calculation的具体函数
function addCalculation(id,value,left,top){
	 
	$("#scope").append("<div class=\"window\" id=\"" + id + "\" style='left:"+left+";top:"+top+"' sourceType=\"calculation\"><h1>" + value + "</h1></div>");
	jsPlumb.draggable(id, {containment : "parent"});
	
	Endpoints[id] = new Array();
	test = jsPlumb.addEndpoint(id, calEndpointIn1);
	Endpoints[id].push(test);
	test = jsPlumb.addEndpoint(id, calEndpointIn2);
	Endpoints[id].push(test);
	test = jsPlumb.addEndpoint(id, calEndpointOut1);
	Endpoints[id].push(test);
	deleteFunction();
	idConuter++;
}

//生成ralation的具体函数
function relationReload(rd){
	if(rd!=null){
	repeatcheck=new Array();
	$.each(rd,function(k,v){
		var leftrightcheck="left";
		if(repeatcheck.indexOf(k)==-1)
		{ 
		           if(v.type=="description")
		           {    
		        	    adddescription(k,v.value,v.left,v.top);
						repeatcheck.push(k);
					}
		}
		if(repeatcheck.indexOf(v.target.ID)==-1)
		{       
			    addCalculation(v.target.ID,v.target.value,v.target.left,v.target.top)
				repeatcheck.push(v.target.ID);
		}
					if(v.order=="leftside")
					{
						jsPlumb.connect({source:k,target:v.target.ID},commonleft);
					}
					else if(v.order=="rightside")
					{
						jsPlumb.connect({source:k,target:v.target.ID},commonright);
					}
	})}
	else{
		alert("Empty Relation")
	}
}

//点击生成description
function adddatasource(){
	$(".btn.btn-default.data").click(
	function(){
		id="flowchartWindow" + idConuter;
		value = $(this).text();
		adddescription(id,value);
		})}
//获取relation数据
function getRelationData() {
    $.ajax({
	url : "../rest/relation/getRelationContent",	
	data : {
	    "path" : $("#pathValue").val()
	},
	dataType : "JSON",
	method : "POST",
	success : function(data) {
		 ;
	    addColumn(data);
	    $("#messageArea").html("add relation success......");
	    reloadData["connections"]=data["connections"];
	     ;
	    if(reloadData["connections"]!=undefined||reloadData["connections"]!=new Object()){
	    	relationReload(reloadData["connections"]);
	    }
	    
	},
	error : function(data) {
	    $("#messageArea").html("connect error, status:" + data.status + " ,message:" + data.statusText);
	}
    }
    );

    }
//从relation数据中获取"csv-key"项，并生成description的button
function addColumn(data)
{   
	dataSource=data;
    var keys=data["csv-key"].split('|');
    $.each(keys,function(k,v){
	$("#columnButtonGroup").append("<button type='button' class='btn btn-default data' >"+v+"</button>");
    }); 
    adddatasource();
 }
//点击生成calculation
function addCal(){
	$(".btn.btn-default.cal").click(
	function(){
		value = $(this).text();
		id="flowchartWindow" + idConuter;
		addCalculation(id,value);
	})}
//双击删除函数（已包含在所有生成函数中，其他地方无需再次调用）
function deleteFunction(){
	$(".window").dblclick(function() {
		var name = $(this).attr("id");
		var i = Endpoints[name].length;
		jsPlumb.detachAllConnections(this);
		$.each(Endpoints[name],function(i){
			jsPlumb.deleteEndpoint(Endpoints[name][i]);	
		}	
		)
		$(this).remove();
	})}
//保存并添加新relation，connection项和translation项
function saveRelation(){
	$("#save-btn").click(
	function(){
		//connection项
		var saveObject=new Object();
		$.each(jsPlumb.getAllConnections(),function(k,v){
			saveObject[v.sourceId]=new Object();
			saveObject[v.sourceId]["value"]=$("#"+v.sourceId).text();
			saveObject[v.sourceId]["top"]=$("#"+v.sourceId).css("top");
			saveObject[v.sourceId]["left"]=$("#"+v.sourceId).css("left");
			saveObject[v.sourceId]["type"]=$("#"+v.sourceId).attr("sourceType");
			if(v.endpoints[1].anchor.x<1){
				saveObject[v.sourceId]["order"]="leftside";
			}else{
				saveObject[v.sourceId]["order"]="rightside";
			}
			saveObject[v.sourceId]["target"]=new Object();
			saveObject[v.sourceId]["target"]["ID"]=v.targetId;
			saveObject[v.sourceId]["target"]["value"]=$("#"+v.targetId).text();
			saveObject[v.sourceId]["target"]["top"]=$("#"+v.targetId).css("top");
			saveObject[v.sourceId]["target"]["left"]=$("#"+v.targetId).css("left");
			saveObject[v.sourceId]["target"]["type"]=$("#"+v.targetId).attr("sourceType");	
		});
		dataSource["connections"]=saveObject;
		testObject=saveObject;
		
		//translation项
        var check= new Array();
        var line = new Object();
        var temp=new Object();
		$.each(dataSource["connections"],function(k,v){
			if(check.indexOf(k)==-1){
         	   if(check.indexOf(v.target.ID)==-1){
         		   line[v.target.ID]=v.value+" "+v.target.value;
         		  temp=line[v.target.ID];
         	   }
         	   else{
         		   line[v.target.ID]=line[v.target.ID]+" "+v.value;
         		  temp=line[v.target.ID];
         	   }
            }
            else{
                if(check.indexOf(v.target.ID)==-1){
             	   line[v.target.ID]="("+line[k]+")"+" "+v.target.value;
             	  temp=line[v.target.ID];
         	   }
         	   else{
         		   line[v.target.ID]=line[v.target.ID]+" "+"("+line[k]+")";
         		  temp=line[v.target.ID];
         	   }
            }
 		   check.push(k);
 		   check.push(v.target.ID);		
		} ) 
		 
//		dataSource["translation"]=line;
		 
		//上传数据
		datasave= JSON.stringify(dataSource);
	    $.ajax({
	    	url : "../rest/relation/editRelationFilter",	    	
	    	data : { "path":$("#pathValue").val() ,
	    		"saveData": datasave,   
	    	},
	    	dataType : "text",
	    	method : "POST",
	    	success : function(data) {
	    	    $("#messageArea").html("save success......");
	    	},
	    	error : function(data) {
	    	    $("#messageArea").html("connect error, status:" + data.status + " ,message:" + data.statusText);
	    	}
	        });
	})}
//重载relation
function addRelation(){
	$("#reload-btn").click(
	function(){
		relationReload(reloadData["connections"]);
	}	)}
//清屏
function clearRelation(){
	$("#clear-btn").click(
	function(){
		var confirmtext=confirm("Clear all relations without save?");
		if (confirmtext==true)
			{
			 
			document.getElementById("scope").innerHTML="";
			alert("All relations cleared");
			delete reloadData["connections"];
			//reloadData["connections"]=new Object();
			}
	})} 
//点击输入特定数据并生成
function inputValues(){
	$(".btn.btn-default.input").click(
	function (){
		value = $("#inputtext").val();
		id = "flowchartWindow" + idConuter;
		adddescription(id,value);
	}		
	)
}

var testObject= new Object();
//测试功能
function testFunction(){
   $("#test-btn").click(
	function autoset(){
		 
		var sourceArea= new Array();
		var targetArea= new Array();
	   	var setcheck=true;
		$.each(testObject,function(k,v){
			sourceArea.push(k);
			targetArea.push(v.target.ID)
		})
       for(var i=0; i<targetArea.length;i++)
			if(sourceArea.indexOf(targetArea[i])==-1  && targetArea[i] != undefined ){
				if(setcheck==true){
					alert("创建"+targetArea[i])
					
					setcheck=false;
				}else{
					setcheck=true
				}
				delete targetArea[i];
				delete sourceArea[i];
			}
			else{setcheck=true}
//				sourceID = sourceArea[k];
//				targetID = targetArea[k];
//				idConuter = idConuter + 1;
//				inputText = saveObject[targetID].value;
//				var divName = "flowchartWindow" + idConuter;
//				$("#scope").append("<div class=\"window\" id=\"" + divName + "\" sourceType=\"calculation\"><h1>" + inputText + "</h1></div>");
//				jsPlumb.draggable(divName, {containment : "parent"});
//				Endpoints[divName] = new Array();
//				test = jsPlumb.addEndpoint(divName, calEndpointIn1);
//				Endpoints[divName].push(test);
//				test = jsPlumb.addEndpoint(divName, calEndpointIn2);
//				Endpoints[divName].push(test);
//				test = jsPlumb.addEndpoint(divName, calEndpointOut1);
//				Endpoints[divName].push(test);
//				idConuter = idConuter + 1;
//				inputText = saveObject[sourceID].value;
//				var divName = "flowchartWindow" + idConuter;
//				$("#scope").append("<div class=\"window\" id=\"" + divName + "\" sourceType=\"description\"><h1>" + inputText + "</h1></div>");
//				jsPlumb.draggable(divName, {containment : "parent"});
//				Endpoints[divName] = new Array();		
//				test = jsPlumb.addEndpoint(divName, dataEndpointOut1);
//				Endpoints[divName].push(test);		
//				deleteFunction();
			
		
	}	   
   )	
}





//main function
$(function() {
     deleteFunction();
     saveRelation();
     clearRelation();
     inputValues();
     testFunction();
     addCal();
     addRelation();
     getRelationData();
})